#include "gu_client.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <getopt.h>

// External variable from getopt
extern int optind;

int main(int argc, char* argv[]) {
    // Create client context
    gu_client_context_t* ctx = gu_client_create();
    if (!ctx) {
        fprintf(stderr, "Failed to create client context\n");
        return 1;
    }
    
    // Parse command line arguments
    int parse_result = gu_client_parse_args(ctx, argc, argv);
    if (parse_result > 0) {
        // Help was shown
        gu_client_destroy(ctx);
        return 0;
    }
    if (parse_result < 0) {
        fprintf(stderr, "Failed to parse arguments\n");
        gu_client_destroy(ctx);
        return 1;
    }
    
    int result = 0;
    
    // Determine mode of operation
    if (ctx->config.interactive || optind >= argc) {
        // Interactive mode or no SQL command provided
        ctx->config.interactive = true;
        
        // Auto-connect in interactive mode
        if (gu_client_connect(ctx) == 0) {
            result = gu_client_interactive_mode(ctx);
        } else {
            fprintf(stderr, "Failed to connect to GuDB server\n");
            printf("Starting in offline mode. Use 'connect' command to connect.\n");
            result = gu_client_interactive_mode(ctx);
        }
    } else {
        // Single command mode
        if (gu_client_connect(ctx) != 0) {
            fprintf(stderr, "Failed to connect to GuDB server\n");
            result = 1;
        } else {
            // Execute the SQL command
            char* sql_command = argv[optind];
            
            // Determine if it's a query or execution
            if (strncasecmp(sql_command, "select", 6) == 0 || 
                strncasecmp(sql_command, "show", 4) == 0 ||
                strncasecmp(sql_command, "describe", 8) == 0 ||
                strncasecmp(sql_command, "explain", 7) == 0) {
                result = gu_client_query_sql(ctx, sql_command);
            } else {
                result = gu_client_execute_sql(ctx, sql_command);
            }
        }
    }
    
    // Cleanup
    gu_client_destroy(ctx);
    
    return result;
}